package com.osexp.model;

import java.util.Vector;

public class TLB implements paraConstants {
	private PTE[] ptes=new PTE[iTLBEntry];
	private Vector<Integer> vPtes=null;


	private int curr;
	public TLB() {
		super();

		curr=0;		
		vPtes=new Vector<Integer>();
		for(int i=0;i<iTLBEntry;i++){
			ptes[i]=new PTE(-1,-1);
			vPtes.add(i);
		}
	}

	public int find(int iLogicalAddress) {		
		int idx=0;
		for(PTE pte:ptes){

			Integer i2=pte.getiLogicalAddress();

			if(i2.equals(iLogicalAddress)){
				//				System.out.println("Found=============================== phyadd="+pte.getiPhysicalAddress());
				
				int rmIdx=vPtes.indexOf(idx);
				vPtes.removeElementAt(rmIdx);
				vPtes.add(idx);
				return pte.getiPhysicalAddress();				
			}else {
				//				System.out.println("Not Found======================================");
			}
			idx++;
		}		
		return -1;
	}

	@Override
	public String toString() {
		String temp="[ptes=" ;
		for(int i= 0 ;i<ptes.length;i++){
			temp += ptes[i].toString()+"\n";
		}
		temp+=", curr=" + curr + "]";
//		return + Arrays.toString(ptes) + ", curr=" + curr + "]";
	return temp;
	}

	public int fifoAdd(int iLogicalAddress,int iPhysicalAddress) {

		ptes[curr].setiLogicalAddress(iLogicalAddress);
		ptes[curr].setiPhysicalAddress(iPhysicalAddress);
		curr=(curr+1)%iTLBEntry;
		return 0;

	}

	public int lruAdd(int iLogicalAddress,int iPhysicalAddress) {
		curr=vPtes.firstElement();
		ptes[curr].setiLogicalAddress(iLogicalAddress);
		ptes[curr].setiPhysicalAddress(iPhysicalAddress);
		vPtes.removeElementAt(0);
		vPtes.add(curr);
		return 0;
	}


	public static void main(String[] args){
		TLB tlb=new TLB();
		tlb.fifoAdd(787, 78);
		tlb.fifoAdd(434, 434);
		tlb.find(787);
		tlb.find(6666);
	}	
}
